<?php
/**[内容模型]
 * @Author: 976123967@qq.com
 * @Date:   2014-08-15 17:05:28
 * @Last Modified by:   chenryoku
 * @Last Modified time: 2014-11-16 11:13:55
 */
class ArticleModel extends Model{
	protected $tableName='article';

	// 自动验证
	public $_validate = array(
		array('category_cid','/^[^0]\d*$/','请选择栏目',1,'regex',3),  
		array('article_title','require','标题不能为空',1,'regex',3),
	);

	// 自动完成
    // array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto = array (
        // 排序转换
        array('sort','intval',3,'function'),
        // 点击次数转换
        array('click','intval',3,'function'),
        // 发布时间
        array('addtime','_addtime',3,'callback'),
        // 编辑时间
        array('edittime','time',3,'function'),
        // 属性
        array('flag','_flag',3,'callback'),
        // user_uid
		array('user_uid','_uid',1,'callback'),
    );

    // 发布时间
    public function _addtime($con)
    {
    	if(!$con)
    		return time();
    	else
    		return strtotime($con);
    }


    // 用户uid
	public function _uid()
	{
		return session('uid');
	}

    // 属性自动完成
	public function _flag()
	{
		$flag = I('post.flag');
		return $flag? implode(',', $flag):'';
	}


    /**
     * [add_article 添加]
     */
	public function add_article()
	{
	
		$data=$this->data;
		// 上传图片
		if(!$pic=$this->alter_pic())
			return false;
		elseif($pic!=1)
		{
			$data['pic']=$pic;
		}
		// 上传文件
		if(!$file = $this->alter_file())
			return false;
		elseif($file!=1)
		{
			$data['file']=$file;
		}
	
		$aid = $this->add($data);
		
		// 图集
		$picModel = D('Pic');
		$attrPic = I('post.attrPic');
		if($attrPic)
			$picModel->add_attr_img($aid);
		else
			$picModel->add_img($aid);
		$this->save_keditor($aid);
		// 添加附表字段值
		$this->add_ext($aid);
		// 添加属性
		D('ArticleAttr')->alert_article_attr($aid);
		

		return $aid;
	}




	/**
	 * [add_ext 添加附表字段值]
	 * @param [type] $aid [description]
	 */
	public function add_ext($aid)
	{
		$cid = I('post.category_cid');
		$mid = D('Category')->get_field($cid,'model_mid');
		$fieldAll = D('Field')->field;
		$field = $fieldAll[$mid];

		$data = array();
		foreach($field as $v)
		{

			// 字段内容值初始化
			$value = '';


			if($v['fname']=='article_aid') continue; 
			// 8文件上传 9图片上传
			if($v['show_type']==8 || $v['show_type']==9)
			{

				$dir = $v['show_type']==9?'image':'file';
				$type = $v['show_type']==9?C('cfg_image'):C('cfg_file');
				$value = $this->upload_ext($v['fname'],$dir,$type);
				// 上传错误
				if($value===false)
					return false;
			}
			// 7是多选
			else if($v['show_type']==7)
			{
				$value = implode(',', $_POST[$v['fname']]);
			}
			else
			{
				$value = $_POST[$v['fname']];
			}
			$data[$v['fname']] = $value;
		}
		// 关联字段
		$data['article_aid'] = $aid;
		$table = 'article_'.D('Model')->get_field($mid,'name');
		
		return M($table)->add($data);
	

	}

	/**
	 * [upload_ext 上传附表中的文件和图片]
	 * @param  [type] $uploadname [description]
	 * @param  [type] $dir        [description]
	 * @param  [type] $type       [description]
	 * @return [type]             [description]
	 */
	public function upload_ext($uploadname,$dir,$type)
	{

		if(!empty($_FILES[$uploadname]['name']))
		{

			// 删除原来的文件
			$aid = I('post.aid');
			if($aid)
			{
				$file = D('ArticleView')->get_field($aid,$uploadname);
				is_file($file) && unlink($file);
			}




			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
			$ext = explode('|', $type);

            $upload->allowExts  = $ext;// 设置附件上传类型
            $savePath = './Data/Uploads/'.$dir.'/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            //is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES[$uploadname],$savePath))
            {
            	//p($info);die;
            	return $info[0]['savepath'].$info[0]['savename'];
            }
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		return '';
	}



	/**
     * [save_article 更新]
     */
	public function save_article()
	{
		$data=$this->data;
		// 上传图片
		if(!$pic=$this->alter_pic())
			return false;
		else if($pic!=1)
		{
			$data['pic']=$pic;
		}
		// 上传文件
		if(!$file = $this->alter_file())
			return false;
		elseif($file!=1)
		{
			$data['file']=$file;
		}
		$this->save($data);
		$aid = I('post.aid',0,'intval');
		// 图集
		$picModel = D('Pic');
		$attrPic = I('post.attrPic');
		if($attrPic)
			$picModel->add_attr_img($aid);
		else
			$picModel->add_img($aid);

		$this->save_keditor($aid);
		// 修改附表字段值
		$this->edit_ext($aid);

		// 添加属性
		D('ArticleAttr')->alert_article_attr($aid);

		return true;
	}



	/**
	 * [edit_ext 修改附表字段值]
	 * @param [type] $aid [description]
	 */
	public function edit_ext($aid)
	{
		$cid = I('post.category_cid');
		$mid = D('Category')->get_field($cid,'model_mid');
		$fieldAll = D('Field')->field;
		$field = $fieldAll[$mid];

		$data = array();
		foreach($field as $v)
		{
			// 字段内容值初始化
			$value = '';

			if($v['fname']=='article_aid') continue; 
			// 8文件上传 9图片上传
			if($v['show_type']==8 || $v['show_type']==9)
			{
				$dir = $v['show_type']==9?'image':'file';
				$type = $v['show_type']==9?C('cfg_image'):C('cfg_file');
				$value = $this->upload_ext($v['fname'],$dir,$type);
				// 上传错误
				if($value === false)
					return false;
			}
			// 7是多选
			else if($v['show_type']==7)
			{
				$value = implode(',', $_POST[$v['fname']]);
			}
			else
			{
				$value = $_POST[$v['fname']];
			}
			// 有内容更新
			if($value)
				$data[$v['fname']] = $value;

			
		}
		$data['article_aid'] = $aid;
		$table = 'article_'.D('Model')->get_field($mid,'name');
		
		M($table)->where(array('article_aid'=>$aid))->save($data);
	
		return true;
	}





	/**
	 * [save_keditor 更新编辑器中的图片]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function save_keditor($aid)
	{
		if(isset($_SESSION['keditor']))
		{
			$uploadModel = D('Upload');
			foreach($_SESSION['keditor'] as $v)
			{
				$data = array(
					'article_aid'=>$aid,
					'id'=>$v,
				);
				$uploadModel->save_upload($data);
			}
			unset($_SESSION['keditor']);
		}
	}


	/**
	 * [find_one 获取单条信息]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function  find_one($aid)
	{
		// 执行模型中的find
		$data=$this->find($aid);
		$data['pic']= $data['pic']?__ROOT__.'/'.$data['pic']:__ROOT__.'/Data/Image/default.gif';

		if(is_file($data['file']))
		{
			$data['size'] = get_size(filesize($data['file']));
		}
		$data['downurl'] = U('down',array('aid'=>$data['aid'],'cid'=>$data['category_cid']));
		return $data;
	}

	/**
	 * [del_article 删除]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function del_article($aid)
	{
		$data = $this->find($aid);

		is_file($data['pic']) && unlink($data['pic']);
		is_file($data['file']) && unlink($data['file']);
	 	
	 	D('Pic')->del_aid_pic($aid);
	 	D('Upload')->del_upload_aid($aid);

	 	$this->del_ext($aid);
	 	D('ArticleAttr')->delete_article_attr($aid);

	 	$this->delete($aid);
	}

	/**
	 * [del_ext 修改]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function del_ext($aid)
	{
		$cid = D('Article')->get_field($aid,'category_cid');
		$mid = D('Category')->get_field($cid,'model_mid');
		$table = 'article_'.D('Model')->get_field($mid,'name');


		$fieldAll = D('Field')->field;
		$field = $field[$mid];
		foreach($field as $v)
		{
			if($v['show_type']==8 || $v['show_type']==9 )
			{
				$file = D('ArticleView')->get_field($aid,$uploadname);
				is_file($file) && unlink($file);
			}
		}

		M($table)->where(array('article_aid'=>$aid))->delete();

	}

	/**
	 * [update_order 排序]
	 * @return [type] [description]
	 */
	public function update_order()
	{
		// 验证
		$aid = I('post.aid');
		if(empty($aid))
		{
			$this->error='没有信息用于排序';
			return false;
		}

		$listOrder= I('post.list_order');
		// 循环更新
		foreach($aid as $k=>$v)
		{
			$data =array(
				'sort'=>$listOrder[$k]
			);
			$this->where(array('aid'=>$v))->save($data);
		}
		return true;
	}


	/**
	 * [update_check update_check]
	 * @param  [type] $sta [description]
	 * @return [type]      [description]
	 */
	public function update_check($sta)
	{
		$aid = I('post.aid');
		if(empty($aid))
		{
			$this->error='没有信息用于审核';
			return false;
		}

		// 循环更改
		foreach($aid as $k=>$v)
		{
			$data =array(
				'verifystate'=>$sta
			);
			$this->where(array('aid'=>$v))->save($data);

		}
		return true;
	}

	/**
	 * [delete_check 删除]
	 * @return [type] [description]
	 */
	public function delete_check()
	{
		// 验证
		$aid = I('post.aid');
		if(empty($aid))
		{
			$this->error='没有信息用于删除';
			return false;
		}
		// 删除
		foreach($aid as $k=>$v)
		{
			$this->del_article($v);
		}
		return true;
	}
	/**
	 * [change_flag 设置属性]
	 * @return [type] [description]
	 */
	public function change_flag($cancel)
	{

		// 验证
		$aid = I('post.aid');
		if(empty($aid))
		{
			$this->error='没有信息用于删除';
			return false;
		}
		$flag = I('post.flag');
		// 设置属性
		foreach($aid as $k=>$v)
		{
			// 把原先的属性取出
			$oldFlag = $this->get_field($v,'flag');

			// 验证是否已经有属性存在
			if(!strchr($oldFlag,$flag) && $cancel==1)
				$oldFlag .=','.$flag;

			if(strchr($oldFlag,$flag) && $cancel==2)
			{
				$oldFlag  = preg_replace('/(,)?'.$flag.'(,)?/', ',', $oldFlag);
			}
			$oldFlag = trim($oldFlag,',');
			
			// 保存
			$this->save(
				array(
					'aid'=>$v,
					'flag'=>$oldFlag
				)
			);
		}
		
		return true;
	}




	/**
	 * [alter_pic 上传图片]
	 * @return [type] [description]
	 */
	public function alter_pic()
	{

		$aid = I('post.aid');
		if($aid&&!empty($_FILES['pic']['name']))
		{
			$field=$this->where("aid=$aid")->field("pic")->find($gid);
			is_file($field['pic']) and unlink($field['pic']);
		}

		if(!empty($_FILES['pic']['name']))
		{
			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
			$ext = explode('|', C('cfg_image'));
            $upload->allowExts  = $ext;// 设置附件上传类型
            $savePath = './Data/Uploads/image/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            //is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES['pic'],$savePath))
                return $info[0]['savepath'].$info[0]['savename'];
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		else
			return 1;
	}



	/**
	 * [alter_file 上传文件]
	 * @return [type] [description]
	 */
	public function alter_file()
	{

		$aid = I('post.aid');
		if($aid&&!empty($_FILES['file']['name']))
		{
			$field=$this->where("aid=$aid")->field("file")->find($gid);
			is_file($field['file']) and unlink($field['file']);
		}

		if(!empty($_FILES['file']['name']))
		{
			// 上传类
			import('ORG.Net.UploadFile');
			$upload = new UploadFile();// 实例化上传类
			$upload->maxSize  = 314572800 ;// 设置附件上传大小
			$ext = explode('|', C('cfg_file'));
            $upload->allowExts  = $ext;// 设置附件上传类型
            $savePath = './Data/Uploads/file/'.date('Y').'/'.date('m').'/'.date('d').'/';
            // 创建目录
            is_dir($savePath) || mkdir($savePath,0777,true);
            // 执行上传
            if($info=$upload->uploadOne($_FILES['file'],$savePath))
                return $info[0]['savepath'].$info[0]['savename'];
            else
            {
            	$this->error=$upload->getErrorMsg();
            	return false;
            }

		}
		else
			return 1;
	}

	/**
	 * [get_article_cid 单篇内容]
	 * @param  [type] $cid [description]
	 * @return [type]      [description]
	 */
	public function get_article_cid($cid)
	{
		return $this->where(array('category_cid'=>$cid))->getField('aid');
	}

	/**
	 * [update_click 更新点击次数]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function update_click($aid)
	{
		$this->where(array('aid'=>$aid))->setInc('click',1);
	}

	/**
	 * [get_field 指定值]
	 * @param  [type] $aid   [description]
	 * @param  [type] $field [description]
	 * @return [type]        [description]
	 */
	public function get_field($aid,$field)
	{
		return $this->where(array('aid'=>$aid))->getField($field);
	}


	/**
	 * [check_article 检查文档是否存在]
	 * @param  [type] $aid [description]
	 * @return [type]      [description]
	 */
	public function check_article($aid)
	{
		return 1;
		//return $this->where(array('aid'=>$aid))->getField('aid');
	}


	/**
	 * [del_attachment 删除上传文件或者删除图片]
	 * @param  [type] $aid   [description]
	 * @param  [type] $field [description]
	 * @param  [type] $field [description]
	 * @return [type]        [description]
	 */
	public function del_attachment($aid,$field,$table)
	{
		// 有$table代表是附表
		if($table)
		{
			// 附表
			$db = M($table);
			$attachment = $db->where(array('article_aid'=>$aid))->getField($field);
		}
		else
		{
			// 主表
			$attachment = $this->get_field($aid,$field);
		}
		
		// 删除文件
		is_file($attachment) && unlink($attachment);

		// 有$table代表是附表
		if($table)
		{
			$db = M($table);
			$db->where(array('article_aid'=>$aid))->save(array($field=>''));
		}
		else
		// 更新数据库
		$this->save(array('aid'=>$aid,$field=>''));
	}


	/**
	 * [set_flag 设置属性对应关系]
	 */
	public function set_flag()
	{
		$key = I('post.key');
		$data = array();
		foreach ($key as $k => $v)
		{
			$data['flag'][$v] = $k;
		}
		return file_put_contents('Data/Config/flag.inc.php', "<?php \nreturn ".var_export($data,true)."; \n?>");
	}


}